package com.toro.server.handler;

import com.toro.message.ChatRequestMessage;
import com.toro.message.ChatResponseMessage;
import com.toro.dao.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: ChatRequestMessageHandler
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/11 17:31
 */
@Slf4j
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatRequestMessage chatRequestMessage) throws Exception {
        log.info("接收到发送消息响应：{}", chatRequestMessage);
        String messageTo = chatRequestMessage.getTo();
        Channel channel = SessionFactory.getSession().getChannel(messageTo);
        ChatResponseMessage message = null;
        if (channel != null) {
            //在线
            ChatResponseMessage chatResponseMessage = new ChatResponseMessage(chatRequestMessage.getFrom(), chatRequestMessage.getContent());
            chatResponseMessage.setSuccess(true);
            channel.writeAndFlush(chatResponseMessage);
            log.info("向：{} 发送的消息 {}", messageTo, chatResponseMessage);
            message = new ChatResponseMessage(true, messageTo + " 收到消息");
        } else {
            //离线
            message = new ChatResponseMessage(false, "对方用户不存在或者不在线");

        }
        channelHandlerContext.writeAndFlush(message);
        log.info("回复发送消息响应：{}", chatRequestMessage);
    }
}
